package ucuserslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"
)

type QueryIncomeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryIncomeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryIncomeListLogic {
	return &QueryIncomeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryIncomeListLogic) QueryIncomeList(req *pb.QueryIncomeListReq) (*pb.QueryIncomeListResp, error) {
	defer utils.RecoverPanic()

	// 处理时间
	var err error
	var start, end *time.Time
	if req.StartTime != "" {
		var t time.Time
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err = time.ParseInLocation(dbkey.DateTimeCNFormat, req.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid start time")
		}
		start = &t
	}
	if req.EndTime != "" {
		var t time.Time
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err = time.ParseInLocation(dbkey.DateTimeCNFormat, req.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid end time")
		}
		end = &t
	}
	// 查询更表数据
	userInviteOrderFlows, err := l.svcCtx.UserInviteOrderFlowModel.Find(l.ctx, req.Uid, req.RebateType, 0, 0, start, end, req.PageNo, req.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, "UserInviteOrderFlowModel.Find error")
	}
	total, err := l.svcCtx.UserInviteOrderFlowModel.Count(l.ctx, req.Uid, req.RebateType, 0, 0, start, end)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, "UserInviteOrderFlowModel.Count error")
	}
	// 查询总收入
	//查询总收入
	inviteTotalIncome, err := l.svcCtx.UserInviteOrderFlowModel.SumOrderAmount(l.ctx, req.Uid, req.RebateType, start, end)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	resp := &pb.QueryIncomeListResp{}
	resp.TotalAmount = inviteTotalIncome
	resp.Total = total
	for _, userInviteOrderFlow := range userInviteOrderFlows {
		incomes := &pb.Incomes{
			RebateType: userInviteOrderFlow.RebateType,
			Type:       userInviteOrderFlow.Type,
			Amount:     decimal.NewFromInt(userInviteOrderFlow.MoneyAmount).StringFixedBank(2),
			CreateTime: userInviteOrderFlow.CreateTime.Format(dbkey.DateTimeCNFormat),
			UpdateTime: userInviteOrderFlow.UpdateTime.Format(dbkey.DateTimeCNFormat),
		}
		resp.List = append(resp.List, incomes)
	}
	return resp, nil
}
